import config from 'config'
import cookie from 'react-cookie'

export function createAjax (mobile = '', code = '', key = '') {
  var createAjax = function (argument) {
    var xmlhttp = {}
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest()
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
    }
    return xmlhttp;
  };
  var data = JSON.stringify({
    'jsonrpc': '2.0',
    'method': 'singUp',
    'params': [{
      'phone': mobile,
      'sms_code': code,
      'key': key
    }],
    'id': 1
  })

  var ajax = new XMLHttpRequest()
  var obj = config
  var that = ''
  var res = ''
  ajax.open('POST', obj.api_root_v1 + '/user.php?c=user', true)
  ajax.withCredentials = true
  // ajax.setRequestHeader('accept', obj.headers['Accept'])
  // ajax.setRequestHeader('content-type', 'application/json')
  ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8')
  ajax.setRequestHeader('authorization', `Bearer ${cookie.load('token')}`)

  var onreadystatechange = function () {
    if (ajax.readyState === 4) {
      if (ajax.status < 400) {
        // res = JSON.parse(ajax.responseText)

      } else {
      }
    }
  }
  ajax.onreadystatechange = onreadystatechange
  ajax.send(data)
  return res
}

export function singUpAjax (mobile = '', code = '', key = '') {
  let res = ''
  let obj = config
  // let cookieToken = cookie.load('token')
  fetch(obj.api_root_v1 + '/user.php?c=user', {
    method: 'POST',
    // mode: 'cors',
    // headers: Object.assign({
    //   // 'Authorization': `${cookie.load('token')}`,
    //   // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    //   // 'Content-Type': 'application/x-www-form-urlencoded'
    //   // 'SHARPRATING_TOKEN': `${cookie.load('SHARPRATING_TOKEN_2')}`
    // }),
    // xhrFields: {
    //   withCredentials: true
    // },
    // credentials: 'include',
    body: JSON.stringify({
      'jsonrpc': '2.0',
      'method': 'singUp',
      'params': [{
        'phone': mobile,
        'sms_code': code,
        'key': key
      }],
      'id': 1
    })
  }).then(function(res) {
    if (res.ok) {
      // res = JSON.parse(ajax.responseText)
    } else if (res.status == 401) {
    }
  }, function(e) {
  })
  return res
}
